# -*- coding=utf-8 -*-
from ShuaPiao import HttpAuto
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import urllib

class TestHTTPHandler(BaseHTTPRequestHandler):
    def do_GET(self):

        if self.path == '/pass_code.jpeg':
            htmlFile = open("pass_code.jpeg")
            html = htmlFile.read()
            htmlFile.close()
            self.protocal_version = "HTTP/1.1"
            self.send_response(200)
            self.send_header("Welcome", "Contect")
            self.send_header("Content-Type", "image/jpeg")
            self.end_headers()
            self.wfile.write(html)

        if self.path.find('/subCode') != -1:
            mpath,margs=urllib.splitquery(self.path)
            if margs:
                code = margs.split("=")[-1]
                codeFile = open("user_code.txt","w+")
                codeFile.write(code)
                codeFile.close()
                self.protocal_version = "HTTP/1.1"
                self.send_response(200)
                self.send_header("Welcome", "Contect")
                self.end_headers()
                self.wfile.write("提交成功")
            else:
                self.protocal_version = "HTTP/1.1"
                self.send_response(200)
                self.send_header("Welcome", "Contect")
                self.end_headers()
                self.wfile.write("提交失败")


        if self.path == '/reflash':
            ha = HttpAuto()
            ha.check_pass_code()
            self.send_response(302)
            self.send_header('Location', "/")
            self.end_headers()

        if self.path == '/':
            htmlFile = open("show.html")
            html = htmlFile.read()
            htmlFile.close()
            self.protocal_version = "HTTP/1.1"
            self.send_response(200)
            self.send_header("Welcome", "Contect")
            self.end_headers()
            self.wfile.write(html)

def start_server(port):
    http_server = HTTPServer(('0.0.0.0', int(port)), TestHTTPHandler)
    http_server.serve_forever() #设置一直监听并接收请求

if __name__ == "__main__":
    start_server(8888)